package com.yvon.maple.gateway.component;

import com.yvon.boot.jwt.utils.JwtUtil;
import com.yvon.maple.constants.SystemConstant;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Collection;

import static com.yvon.maple.constants.SystemConstant.Common.TOKEN_HEADER;

/**
 * 令牌的身份验证管理器
 *
 * @author : Yvon
 * @since : 2021-11-30
 */
@Component
@Primary
public class TokenAuthenticationManager implements ReactiveAuthenticationManager {

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
            return Mono.just(authentication)
                    .map(auth -> JwtUtil.getClaims(auth.getPrincipal().toString(), 0))
                    .map(claims -> {
                        Collection<String> roles = (Collection<String>)
                                claims.get(TOKEN_HEADER);

                        Collection<GrantedAuthority> authorities = new ArrayList<>();
                            if (roles != null) {
                                roles.forEach(item -> authorities.add((GrantedAuthority) () -> item)
                                );
                            }

                        return new UsernamePasswordAuthenticationToken(
                                claims.getSubject(),
                                null,
                                authorities
                        );
                    });
    }
}
